<!doctype html>
<html lang="en">

<head>
    <title>GET VIDEO</title>
    <meta charset="utf-8">
    <script src="{{ url_for('static', filename='js/jquery-1.7.1.min.js') }}"></script>
    <script type="text/javascript" src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
    <style>
        .flex {
            display: flex;
            justify-content: space-around;
        }

        .flex>* {
            background: black;
            width: 25vw;
            height: 25vw;
        }
    </style>
</head>

<body>
    <div class="flex">
        <video id="video" autoplay="autoplay"></video>
        <canvas id="canvas"></canvas>
        <img id="result" src="" />
    </div>
    <div style="text-align: center; padding: 5vh 0;">
        <input type="button" title="开启摄像头" value="开启摄像头" onclick="getMedia()" />
{#        <button id="upload" onclick="uploadImage()">拍照</button>#}
{#        <button id="close" onclick="closeMedia()">关闭</button>#}
        <button id="auto" onclick="autouploadImage()">五官</button>
        <button id="autodetectFace" onclick="autodetectFace()">人脸关键点</button>
        <button id="emotionRecognition" onclick="emotionRecognition()">人脸表情</button>
        <button id="faceswap" onclick="faceswap()">换脸</button>
        <button id="facesearch" onclick="facesearch()">身份识别</button>

    </div>

    <script>
        var intervalId = null;
        function autouploadImage() {
          if(intervalId) clearInterval(intervalId);
          intervalId = window.setInterval(uploadImage, {{ period }});
        }
        function closeMedia() {
            var video = document.getElementById('video');
            if (!video.srcObject) return
            let stream = video.srcObject;
            let tracks = stream.getTracks();
            tracks.forEach(track => {
                track.stop()
            })
            if(intervalId) clearInterval(intervalId);
        }
        //获得video摄像头区域
        let video = document.getElementById("video");
        function getMedia() {
            let constraints = {
                video: { width: 500, height: 500 },
                audio: false
            };

            /*
            这里介绍新的方法:H5新媒体接口 navigator.mediaDevices.getUserMedia()
            这个方法会提示用户是否允许媒体输入,(媒体输入主要包括相机,视频采集设备,屏幕共享服务,麦克风,A/D转换器等)
            返回的是一个Promise对象。
            如果用户同意使用权限,则会将 MediaStream对象作为resolve()的参数传给then()
            如果用户拒绝使用权限,或者请求的媒体资源不可用,则会将 PermissionDeniedError作为reject()的参数传给catch()
            */
            let promise = navigator.mediaDevices.getUserMedia(constraints);
            promise.then(function (MediaStream) {
                video.srcObject = MediaStream;
                video.play();
            }).catch(function (PermissionDeniedError) {
                console.log(PermissionDeniedError);
            })
        }

        function takePhoto() {
            //获得Canvas对象
            let canvas = document.getElementById("canvas");
            let ctx = canvas.getContext('2d');
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        }

        function setImage(base64) {
            const dom = document.querySelector('#result');
            dom.src = base64;
        }

        //图片上传到服务器
        //获取Canvas的编码
        // < !--var video = document.getElementById('video'); -->
        var canvas = document.getElementById('canvas');
        var context = canvas.getContext('2d');
        function uploadImage() {
            canvas.width = 300;
            canvas.height = 300;
            context.drawImage(video, 0, 0, 300, 300);

            // Example

            var imgData = canvas.toDataURL("image/jpg");
            imgData = imgData.replace(/^data:image\/(png|jpg);base64,/, "")
            //上传到后台。
            var uploadAjax = $.ajax({
                type: "post",
                //后端需要调用的地址
                url: "/receiveImage/",
                data: imgData,   //JSON.stringify({ "imgData": imgData }),
                contentType: "text/application",
                //设置超时
                timeout: 10000,
                async: true,
                success: function (resultBase64) {
                    // 把返回结果显示到dom中
                    //成功后回调
                    // resultBase64 = JSON.parse(resultBase64)
                    setImage(resultBase64);
                },
                error: function (data) {
                },
                //调用执行后调用的函数
                complete: function (XMLHttpRequest, textStatus) {
                    if (textStatus == 'timeout') {
                        uploadAjax.abort(); //取消请求
                        //超时提示：请求超时，请重试
                        alert("请求超时，请重试")
                        //请求超时返回首页
                        closeCard();
                    }
                }
            });
        }



        //自动识别人脸框
        function autodetectFace(){
            function autodetectFace_f() {
                canvas.width = 300;
                canvas.height = 300;
                context.drawImage(video, 0, 0, 300, 300);

                // Example

                var imgData = canvas.toDataURL("image/jpg");
                imgData = imgData.replace(/^data:image\/(png|jpg);base64,/, "")
                //上传到后台。
                var uploadAjax = $.ajax({
                    type: "post",
                    //后端需要调用的地址
                    url: "/autodetectFace/",
                    data: imgData,   //JSON.stringify({ "imgData": imgData }),
                    contentType: "text/application",
                    //设置超时
                    timeout: 10000,
                    async: true,
                    success: function (resultBase64) {
                        // 把返回结果显示到dom中
                        //成功后回调
                        // resultBase64 = JSON.parse(resultBase64)
                        setImage(resultBase64);
                    },
                    error: function (data) {
                    },
                    //调用执行后调用的函数
                    complete: function (XMLHttpRequest, textStatus) {
                        if (textStatus == 'timeout') {
                            uploadAjax.abort(); //取消请求
                            //超时提示：请求超时，请重试
                            alert("请求超时，请重试")
                            //请求超时返回首页
                            closeCard();
                        }
                    }
                });
            }
            if(intervalId) clearInterval(intervalId);
            intervalId = window.setInterval(autodetectFace_f, {{ period }});
        }



        //自动识别人脸表情
        function emotionRecognition(){
            function emotionRecognition_f() {
                canvas.width = 300;
                canvas.height = 300;
                context.drawImage(video, 0, 0, 300, 300);

                // Example

                var imgData = canvas.toDataURL("image/jpg");
                imgData = imgData.replace(/^data:image\/(png|jpg);base64,/, "")
                //上传到后台。
                var uploadAjax = $.ajax({
                    type: "post",
                    //后端需要调用的地址
                    url: "/emotionRecognition/",
                    data: imgData,   //JSON.stringify({ "imgData": imgData }),
                    contentType: "text/application",
                    //设置超时
                    timeout: 10000,
                    async: true,
                    success: function (resultBase64) {
                        // 把返回结果显示到dom中
                        //成功后回调
                        // resultBase64 = JSON.parse(resultBase64)
                        setImage(resultBase64);
                    },
                    error: function (data) {
                    },
                    //调用执行后调用的函数
                    complete: function (XMLHttpRequest, textStatus) {
                        if (textStatus == 'timeout') {
                            uploadAjax.abort(); //取消请求
                            //超时提示：请求超时，请重试
                            alert("请求超时，请重试")
                            //请求超时返回首页
                            closeCard();
                        }
                    }
                });
            }
            if(intervalId) clearInterval(intervalId);
            intervalId = window.setInterval(emotionRecognition_f, {{ period }});
        }


        //换脸
        function faceswap(){
            function faceswap_f() {
                canvas.width = 300;
                canvas.height = 300;
                context.drawImage(video, 0, 0, 300, 300);

                // Example

                var imgData = canvas.toDataURL("image/jpg");
                imgData = imgData.replace(/^data:image\/(png|jpg);base64,/, "")
                //上传到后台。
                var uploadAjax = $.ajax({
                    type: "post",
                    //后端需要调用的地址
                    url: "/faceswap/",
                    data: imgData,   //JSON.stringify({ "imgData": imgData }),
                    contentType: "text/application",
                    //设置超时
                    timeout: 10000,
                    async: true,
                    success: function (resultBase64) {
                        // 把返回结果显示到dom中
                        //成功后回调
                        // resultBase64 = JSON.parse(resultBase64)
                        setImage(resultBase64);
                    },
                    error: function (data) {
                    },
                    //调用执行后调用的函数
                    complete: function (XMLHttpRequest, textStatus) {
                        if (textStatus == 'timeout') {
                            uploadAjax.abort(); //取消请求
                            //超时提示：请求超时，请重试
                            alert("请求超时，请重试")
                            //请求超时返回首页
                            closeCard();
                        }
                    }
                });
            }
            if(intervalId) clearInterval(intervalId);
            intervalId = window.setInterval(faceswap_f, 500);
        }


        //换脸
        function facesearch(){
            function facesearch_f() {
                canvas.width = 300;
                canvas.height = 300;
                context.drawImage(video, 0, 0, 300, 300);

                // Example

                var imgData = canvas.toDataURL("image/jpg");
                imgData = imgData.replace(/^data:image\/(png|jpg);base64,/, "")
                //上传到后台。
                var uploadAjax = $.ajax({
                    type: "post",
                    //后端需要调用的地址
                    url: "/facesearch/",
                    data: imgData,   //JSON.stringify({ "imgData": imgData }),
                    contentType: "text/application",
                    //设置超时
                    timeout: 10000,
                    async: true,
                    success: function (resultBase64) {
                        // 把返回结果显示到dom中
                        //成功后回调
                        // resultBase64 = JSON.parse(resultBase64)
                        setImage(resultBase64);
                    },
                    error: function (data) {
                    },
                    //调用执行后调用的函数
                    complete: function (XMLHttpRequest, textStatus) {
                        if (textStatus == 'timeout') {
                            uploadAjax.abort(); //取消请求
                            //超时提示：请求超时，请重试
                            alert("请求超时，请重试")
                            //请求超时返回首页
                            closeCard();
                        }
                    }
                });
            }
            if(intervalId) clearInterval(intervalId);
            intervalId = window.setInterval(facesearch_f, 1000);
        }


    </script>
</body>

</html>